import Koa from "koa";
import serve from "koa-static";
import session from "koa-session";
import views from "koa-views";
import bodyparser from "koa-bodyparser";
import path from "path";
import { config } from "../config";
import { createConnection } from "typeorm";
import { Logs } from "../utils/logs";
import { logger } from "../utils/logger";

export default class initPlugins {
  // 所有需要配置参数的中间件集合
  public Pluginslist!: Array<any>;
  public Koa2: any = new Koa();

  constructor() {
    this.inputPlugins();
  }

  //挂载中间件
  public async inputPlugins() {
    // 设置签名的 Cookie 密钥。
    this.Koa2.keys = [config.initPlugins.SessionKey];

    this.Pluginslist = [
      // 记录系统日志，访问级别的，记录用户的所有请求，作为koa的中间件
      Logs.AccessLogger(),
      //处理post请求
      bodyparser(),
      // 静态资源配置
      serve(config.initPlugins.staticPath, { maxage: 0 }),
      // session 配置
      session(
        {
          key: "koa:sess",
          maxAge: 36000000,
          overwrite: true,
          httpOnly: false,
          signed: true,
          rolling: false,
          renew: false,
        },
        this.Koa2
      ),
      //模板引擎配置
      views(config.initPlugins.viewsPath, {
        extension: "pug",
      }),
    ];
   await this.initrun();
  }
  public  async initrun() {
    try {
      //foreach 挂载
      this.Pluginslist.forEach((v) => this.Koa2.use(v));
      //挂载typeorm
      // @ts-ignore
      await createConnection(config.typeorm);
    } catch (e) {
      // 终端输出
      logger.logSymbolsError(`配置插件出错：${e} `);
      Logs.ApplicationLogger().error(e);
    }
  }
}
